<?php
/**
 * Created by PhpStorm.
 * User: user
 * Date: 2017/2/13
 * Time: 17:25
 */
namespace haibao\jiepai\data;

use haibao\jiepai\model\filter\file\CmsFiles as CmsFilesFilter;
use haibao\frame\data\query\Condition;

class Files extends \haibao\jiepai\data\BaseMysql{
	
	public function __construct(){
		parent::__construct('\haibao\jiepai\model\data\file\CmsFiles');
	}

    public function saveImageInfo($fileInfo, $storagePath, $userId){
    	$this->beginTranscation();
    	try{
    		$fileModel = $this->packFileInfoFilter($fileInfo, $storagePath, $userId);
    		$this->add($fileModel);
    	} catch(\Exception $e){
    		throw $e;
    	}
    	$this->endtranscation();
    	return $fileInfo;
    }

    public function insertFile($fileName){
        $sql = 'INSERT INTO cms_files (ServerFileName) VALUES (%s)';
        $this->query($sql,array($fileName));
        return $this->getDb()->insert_id;
    }
    
    /**
     * 保存实体
     */
    public function packFileInfoFilter($fileInfo, $storagePath, $userId){
    	$cmsFileFilter = new CmsFilesFilter();
    	$cmsFileFilter = array(
    			CmsFilesFilter::CONDITION_FIELD_NAME_CREATE_TIME => new \DateTime(),
    			CmsFilesFilter::CONDITION_FIELD_NAME_FILE_SIZE => $fileInfo['size'],
    			CmsFilesFilter::CONDITION_FIELD_NAME_FILE_HEIGHT => $fileInfo['height'],
    			CmsFilesFilter::CONDITION_FIELD_NAME_FILE_WIDTH => $fileInfo['width'],
    			CmsFilesFilter::CONDITION_FIELD_NAME_SERVER_FILE_NAME => $storagePath,
    			CmsFilesFilter::CONDITION_FIELD_NAME_USER_ID => $userId
    	);
    	return $cmsFileFilter;
    }
    
    /**
     * 根据id获取图片信息
     */
    public function getImageById($imageId){
    	$imageId = (array)$imageId;
    
    	$query = new \haibao\jiepai\model\filter\file\CmsFiles();
    	$query->where(\haibao\jiepai\model\filter\file\CmsFiles::CONDITION_FIELD_NAME_ID, Condition::CONDITION_IN, $imageId);
    
    	return $this->getAll($query);
    }
    
}